﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>
/******* Stock ********/
$(function () {
    //debugger;
    var dates = $("#txtTransactionDate, #txtValueDate").datepicker({
        defaultDate: "+1d",
        changeMonth: true,
        //numberOfMonths: 3,
        showOn: 'button',
        buttonImage: '/images/Icons/calendar.gif',
        buttonImageOnly: true,
        onSelect: function (selectedDate) {
            var option = this.id == "txtTransactionDate" ? "minDate" : "maxDate",
					instance = $(this).data("datepicker"),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings);
            dates.not(this).datepicker("option", option, date);
        }
    });


    $("#ddlStock").change(StockChange);
    function StockChange() {
        var stockValue = $("#ddlStock").val();
        if (stockValue != null) {

            var stockValues = stockValue.split("_");
            $("#stockCurrency ").text(stockValues[1]);
            $("#ddlStockSelected").val(stockValues[0]);
        }
    }

    $(".Calc").change(function () {
        var value = $(this).val();
        if (isNaN(value) || value == "") {
            $(this).val(0);
        }
        //debugger;
        var isBuy = ($("#rbStockBuy")[0].checked) ? -1 : 1;
        var stock = parseInt($("#txtQuantity").val());
        var perShare = parseFloat($("#txtPerShare").val());
        var flat = parseFloat($("#txtFlat").val());
        var price = parseFloat($("#txtPrice").val());
        var totalFees = -1 * (stock * perShare + flat);
        $("#txtTotalFees").val(totalFees);
        $("#txtTotalConsideration").val(stock * price * isBuy + totalFees);
    });


    $("#btnSaveStock").click(function () {
        //debugger;
        var message = "";

        var from = $("#txtTransactionDate").datepicker("getDate");
        var to = $("#txtValueDate").datepicker("getDate");
        if (isNaN(from) || isNaN(to) || from > to) {
            message = "Transaction Date cannot be bigger then Value Date.";
        }
        if ($("#txtQuantity").val() == 0) {
            message += "Quantity cannot be zero.";
        }
        if ($("#txtPrice").val() < 0) {
            message += "Price cannot be less then zero";
        }
        $("#lblStockMsg").text(message);

        if (message != "") { return false; }

        var clientId = $("#lblOrganisationId").text();
        var ddlEntity = $("#ddlStockEntity").val();
        var counterparty = $("#ddlStockCounterparty").val();
        var transactionRef = $("#txtStockTransactionRef").val();
        var buySell = $("#rbStockBuy")[0].checked ? "B" : "S";
        var stock = $("#ddlStockSelected").val();
        var quantity = $("#txtQuantity").val();
        quantity = (buySell == "B") ? quantity : -1 * quantity;
        var price = $("#txtPrice").val();
        var perShare = $("#txtPerShare").val();
        var flat = $("#txtFlat").val();
        var totalFees = $("#txtTotalFees").val();
        var totalConsideration = $("#txtTotalConsideration").val();
        var service = new TreaShares.Services.TransactionAdd();
        $('#tabs-1 :input').attr('disabled', true);
        service.Share(clientId, from, to, ddlEntity, counterparty, transactionRef, buySell, stock, quantity, price, perShare,
                flat, totalFees, totalConsideration, StockSucceeded, AjaxFailed, null);
        //$(this).
    });
    StockChange();
    /********* Option **********/

    $("#ddlOptionStock").change(OptionStockChange);
    function OptionStockChange() {
        var stockValue = $("#ddlOptionStock").val();
        if (stockValue != null) {

            var stockValues = stockValue.split("_");
            $("#optionCurrency ").text(stockValues[1]);
            $("#txtOptionStockSelected").val(stockValues[0]);
        }
    }


    var dates1 = $("#txtTransactionOptionDate, #txtOptionValueDate").datepicker({
        defaultDate: "+1d",
        changeMonth: true,
        showOn: 'button',
        buttonImage: '/images/Icons/calendar.gif',
        buttonImageOnly: true,
        onSelect: function (selectedDate) {
            var option = this.id == "txtTransactionOptionDate" ? "minDate" : "maxDate",
					instance = $(this).data("datepicker"),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings);
            dates1.not(this).datepicker("option", option, date);
        }
    });
    $("#btnSaveOption").click(function () {
        //debugger;
        var message = "";
        var transactionDate = $("#txtTransactionOptionDate").datepicker("getDate");
        var valueDate = $("#txtOptionValueDate").datepicker("getDate");
        var vestingDate = $("#txtVestingDate").datepicker("getDate");
        var exerciseDate = $("#txtExerciseDate").datepicker("getDate");
        var ulOption = $("#ulOption");
        ulOption.empty();
        var isValid = true;
        if (isNaN(transactionDate)) {
            ulOption.append('<li>Transaction Date is invalid.</li>');
            isValid = false;
        }
        if (isNaN(valueDate) || valueDate < transactionDate) {
            ulOption.append('<li>Value Date is invalid.</li>');
            isValid = false;
        }
        if (isNaN(vestingDate) || vestingDate < valueDate) {
            ulOption.append('<li>Vesting Date is invalid.</li>');
            isValid = false;
        }
        if (isNaN(exerciseDate) || exerciseDate < valueDate) {
            ulOption.append('<li>Exercise Date is invalid.</li>');
            isValid = false;
        }
        if ($("#txtOptionQuantity").val() <= 0) {
            ulOption.append('<li>Quantity must be bigger then zero.</li>');
            isValid = false;
        }
        if ($("#txtStrike").val() <= 0) {
            ulOption.append('<li>Strike cannot be zero.</li>');
            isValid = false;
        }

        //$("#lblOptionMsg").text(message);
        if (!isValid) { return; }
        var clientId = $("#lblOrganisationId").text();
        var ddlEntity = $("#ddlOptionEntity").val();
        var counterparty = $("#ddlOptionCounterparty").val();
        var transactionRef = $("#txtOptionTransactionRef").val();
        var buySell = $("#rbOptionBuy")[0].checked ? "B" : "S";
        var stock = $("#txtOptionStockSelected").val();
        var quantity = $("#txtOptionQuantity").val();
        quantity = (buySell == "B") ? quantity : -1 * quantity;
        var strike = $("#txtStrike").val();
        var premium = $("#txtPremium").val();
        var exerciseType = $("#txtExerciseTypeCash")[0].checked ? "Cash" : "Physical";
        var service = new TreaShares.Services.TransactionAdd();
        $('#tabs-2 :input').attr('disabled', true);
        service.Option(clientId, transactionDate, valueDate, ddlEntity, counterparty, transactionRef, buySell, vestingDate, exerciseDate,
                stock, quantity, strike, premium, exerciseType, OptionSucceeded, AjaxFailed, null);
    });
    $("#tabs").tabs({ selected: defaultNewTransactionJS });
    OptionStockChange();
    $("#btnPrice").click(function () {
        $("#priceOptionDialog").dialog("open");
        return false;
    });
    $("#priceOptionDialog").dialog({
        autoOpen: false,
        show: "blind",
        hide: "explode",
        width: 450,
        height: 400,
        position: 'top',
        modal: true,
        open: function (event, ui) {
            $("#txtPricerValueDate").val($("#txtOptionValueDate").val());
            $("#txtPricerVestingDate").val($("#txtVestingDate").val());
            $("#txtPricerStrike").val($("#txtStrike").val());
            $("#txtPricerMaturityDate").val($("#txtExerciseDate").val());
        }
    });
    $("#btnPriceOption").click(function () {
        var service = new TreaShares.Services.TransactionAdd();
        var lossRate = $("#txtPricerLossRate").val();
        var volatility = $("#txtPricerVolatility").val();
        var dividendRate = $("#txtPricerDividendYield").val();
        var growthRate = $("#txtPricerGrowthRate").val();
        var quantity = $("#txtOptionQuantity").val();
        var stockPrice = $("#txtStockPrice").val();
        var strike = $("#txtPricerStrike").val();

        var maturityDate = new Date($("#txtPricerMaturityDate").val());
        var vestingDate = new Date($("#txtPricerVestingDate").val());
        var valueDate = new Date($("#txtPricerValueDate").val());


        service.PriceOption(valueDate, vestingDate, maturityDate,quantity, stockPrice, strike, growthRate, dividendRate, volatility, lossRate, PriceOptionSucceeded, PriceOptionFailed, null);
    });


    $("#txtTransactionDate , #txtValueDate, #txtTransactionOptionDate, #txtOptionValueDate").datepicker('setDate', todayDate);

});

function OptionSucceeded(result) {
    $('#tabs-2 :input').removeAttr('disabled');
    $("#lblOptionMsg").text("Option Transaction# " + result + " saved");
    $("#txtOptionQuantity").val(0);
    $("#txtStrike").val(0);
    $("#txtPremium").val(0);
}
function StockSucceeded(result) {
    $('#tabs-1 :input').removeAttr('disabled');
    $("#lblStockMsg").text("Stock Transaction# " + result + " saved");
    $("#txtQuantity").val(0);
    $("#txtPrice").val(0);
    $("#txtPerShare").val(0);
    $("#txtFlat").val(0);
    $("#txtTotalFees").val(0);
    $("#txtTotalConsideration").val(0);
}
function AjaxFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

function PriceOptionFailed(result) { alert(result.status + ' ' + result.statusText); }
function PriceOptionSucceeded(result) {
    //var quantity = $("#txtOptionQuantity").val();
    //var npv = result * quantity;
    $("#lblOptionPriceMsg").text(result);
}
function PriceOptionFailed(result) { alert(result); }